<?php

namespace App\Admin\Controllers;

use App\Models\WhiteList;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Controllers\AdminController;

class WhiteController extends AdminController
{
    protected $title = '白名单';

    protected function grid()
    {
        $grid = new Grid(new WhiteList());

        $grid->column('id', 'ID');
        $grid->column('user_id', '会员')->display(function () {
            return $this->user->nameText(true);
        });
        $grid->column('is_always', '是否永久白名单')->bool();
        
         $grid->column('expired_at', '过期时间')->display(function () {
            return $this->expired_at;
        });
        
        $grid->disableExport();
        $grid->disableRowSelector();
        
        $this->gridActions($grid);

        return $grid;
    }
    
    protected function gridActions(Grid $grid)
    {
	    $grid->actions(function (Grid\Displayers\Actions $actions) {
	    	$actions->disableView();
	    });
    }
    
    protected function form()
    {
        $form = new Form(new WhiteList());

        $form->select('user_id', '会员')->options(User::all()->pluck('name', 'id'))
            ->rules('required');

  

        $form->radio('is_always', '是否永久白名单')->options(config('site.bool'))->default(false);
        $form->date('expired_at', '过期时间');

        $this->formTools($form);
        $this->formFooter($form);
        $this->formSaving($form);

        return $form;
    }
    
    protected function formTools(Form $form)
    {
    	$form->tools(function (Form\Tools $tools) {
		    $tools->disableView();
	    });
    }
    
    protected function formFooter(Form $form)
    {
	    $form->footer(function (Form\Footer $footer) {
		    $footer->disableViewCheck();
		    $footer->disableCreatingCheck();
		    $footer->disableEditingCheck();
	    });
    }

     protected function formSaving(Form $form)
    {
        $form->saving(function (Form $form) {
            // Passowrd for editing mode
           $white = WhiteList::query()->where("user_id",$form->user_id)->where('is_always',true)->first();
           if($white){

                admin_toastr('该用户已经是永久白名单', 'error');
                return redirect('/admin/white');
           }
        });
    }

}
